<?php
/**
 * Created by PhpStorm.
 * User: yy
 * Date: 2019/6/26
 * Time: 17:20
 */

namespace app\common\service\environmentAnalysis;


use think\Db;
use think\facade\Config;
use app\common\service\CommonService;
use app\common\service\airquality\AirQualityStationAqiRealtimeDayService;
use app\common\service\lastWeek\LastWeekControlAnalysisService;


class EnvironmentAnalysisControlService
{
    /**
     * 行业运行趋势图
     * @author yy by 2019/6/27
     * @param array $param
     * @return array
     */
    public function getIndustryOperationTrend($param = [])
    {
        $commonService      = new CommonService();
        $industry_limit_arr = $commonService->getIndustryLimitIdmysql();
        $companyIdArr       = $commonService->getCompanyIdArr(1);
        $dayService         = new AirQualityStationAqiRealtimeDayService();
        $days               = $dayService->diffDays($param['start_time'], $param['end_time']);
        # 脱硫脱硝判断 影响运行浓度、运行效率、排放量
        if (strtolower($param['pollutant_name']) == 'so2') {
            $table                   = 'company_industry_monitor_sulfur_day';
            $operation_concentration = 'operation_concentration_so2';
            $operating_efficiency    = 'operating_efficiency_so2';
        } else {
            $table                   = 'company_industry_monitor_nitre_day';
            $operation_concentration = 'operation_concentration_nox';
            $operating_efficiency    = 'operating_efficiency_nox';
        }
        # 模拟表(排除掉晋能长治热电有限公司)（不用判断时间）
        $hours_simulate = $days * 24;
        $hours_real     = Config::get('hours_real');
        $data_simulate  = Db::query("select avg($operation_concentration) as operation_concentration, avg($operating_efficiency) as operating_efficiency, industry_id, industry_name
                                from company_industry_monitor_simulation_day_avg
                                where company_id in $companyIdArr and industry_id = ?
                                ", [$param['industry_id']]);
        # 脱硫表或脱硝表（查时间区间）
        $data_real = Db::query("select avg(operation_concentration) as operation_concentration, avg(operating_efficiency) as operating_efficiency, industry_id, industry_name, DATE_FORMAT(publish_time, '%Y-%m-%d') as date
                                from $table
                                where power = 1 and industry_id = ? and DATE_FORMAT(publish_time, '%Y-%m-%d') between ? and ?
                                group by publish_time", [$param['industry_id'], $param['start_time'], $param['end_time']]);
        $list      = [];
        if ($param['industry_id'] == Config::get('company_jinneng')) {
            # 电力行业 运行浓度 & 运行效率
            foreach ($data_simulate as $k1 => $v1) {
                // 电力行业模拟表的每天的数据相同
                $simulate['operation_concentration'] = $v1['operation_concentration'];
                $simulate['operating_efficiency']    = $v1['operating_efficiency']; //运行效率前台显示百分比
                // 如果晋能热电有实测数据
                for ($m = 0; $m < count($data_real); $m++) {
                    if ($data_real[$m]['industry_id'] == $v1['industry_id']) { //模拟表和脱硫脱硝表重复的只有电力（晋能热电）这个行业
                        $data_real[$m]['operation_concentration'] = ($data_real[$m]['operation_concentration'] + $v1['operation_concentration']) / 2; //电力行业的运行浓度
                        $data_real[$m]['operating_efficiency']    = ($data_real[$m]['operating_efficiency'] + $v1['operating_efficiency']) / 2;  //电力行业的运行效率
                    }
                }
            }
            $lastWeekControlAnalysisService = new LastWeekControlAnalysisService();
            $list['concentration']          = $lastWeekControlAnalysisService->getAllData($param, $data_real, 'operation_concentration');
            for ($x = 0; $x < count($list['concentration']['date']); $x++) { //响应时段行业企业管控平均值
                $list['concentration']['data'][1][$x] = '-';
            }
            $list['efficiency'] = $lastWeekControlAnalysisService->getAllData($param, $data_real, 'operating_efficiency');
            for ($x = 0; $x < count($list['efficiency']['date']); $x++) { //响应时段行业企业管控平均值
                $list['efficiency']['data'][1][$x] = '-';
            }
        } else {
            # 其他行业 运行浓度 & 运行效率
            $date_all = $commonService->getDate($param['start_time'], $param['end_time']);
            for ($i = 0; $i < count($date_all); $i++) {
                $list['concentration']['date'][$i]    = $date_all[$i];
                $list['concentration']['data'][0][$i] = $data_simulate[0]['operation_concentration'];
                $list['concentration']['data'][1][$i] = '-'; //响应时段行业企业管控平均值
                $list['efficiency']['date'][$i]       = $date_all[$i];
                $list['efficiency']['data'][0][$i]    = $data_simulate[0]['operating_efficiency'];
                $list['efficiency']['data'][1][$i]    = '-'; //响应时段行业企业管控平均值
            }
        }
        return $list;
    }

    /**
     * 行业贡献度趋势图
     * @author yy by 2019/6/29
     */
    public function getIndustryContributionTrend($param=[])
    {
        $list              = [];
        $commonService     = new CommonService();
        $newTime           = $commonService->getMongoTime($param);
        $mongodb_huanxin   = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        $document          = [
            'aggregate'    => Config::get('contribution_table_name'),
            'pipeline'     => [
                [
                    '$project' => [
                        'predict_time'        => 1,
                        'publish_time'        => 1,
                        'contribution_name'   => 1,
                        'company_id'          => 1,
                        'industry_id'         => 1,
                        'station_id'          => 1,
                        'region_id'           => 1,
                        'contribution_value'  => 1, //贡献度
                        'contribution_degree' => 1, //贡献值
                        'concentration'       => 1,
                        'difference'          => ['$eq' => ['$publish_time', '$predict_time']]
                    ],
                ],
                [
                    '$match' => [
                        'difference'        => true,
                        'region_id'         => (int)$param['region_id'],
                        'station_id'        => (int)$param['station_id'],
                        'industry_id'       => (int)$param['industry_id'],
                        'contribution_name' => strtoupper($param['pollutant_name']),
                        'predict_time'      => [
                            '$gte' => $newTime['start_time'],
                            '$lte' => $newTime['end_time'],
                        ],
                    ]
                ],
                [
                    '$group' => [
                        '_id'               => ['publish_time' => '$publish_time'],
                        'total'             => ['$sum' => '$contribution_degree'], // TODO 指定行业一天的贡献值 = 这个行业下不同企业同一天贡献值 相加
                        'concentration_sum' => ['$avg' => '$concentration'] //该站点这一天的浓度
                    ]
                ],
                [
                    '$sort' => [
                        '_id' => 1,
                    ]
                ]
            ],
            'allowDiskUse' => true,
        ];
        $command           = new \MongoDB\Driver\Command($document);
        $rows              = $mongodb_huanxin->executeCommand('huanxin', $command)->toArray();
        $contribution_data = json_decode(json_encode($rows, 320), true);
        $date_all          = $commonService->getDate($param['start_time'], $param['end_time']);
        $num               = count($contribution_data[0]['result']);
        if ($num > 0) {
            foreach ($contribution_data[0]['result'] as $k => $v) {
                $list['date'][]    = date('Y-m-d', strtotime($v['_id']['publish_time']));
                $list['data'][0][] = $v['concentration_sum'] > 0 ? $commonService->contributionRound($v['total'] / $v['concentration_sum']) : '';
            }
            # 比较差集
            $different     = array_values(array_diff($date_all, $list['date']));
            $different_num = count($different);
            if ($different_num > 0) {
                for ($i = 0; $i < $different_num; $i++) {
                    $list['date'][]    = $different[$i];
                    $list['data'][0][] = '-';
                }
            }
        } else {
            $list['date'] = $date_all;
            for ($i = 0; $i < count($list['date']); $i++) {
                $list['data'][0][$i] = '-';
            }
        }
        # 依据publish_time排序
        array_multisort($list['date'], $list['data'][0]);
        for ($m = 0; $m < count($list['date']); $m++) {
            $list['date'][$m]    = date('m/d', strtotime($list['date'][$m]));
//            $list['data'][0][$m] > 0 ? $list['data'][0][$m] = $list['data'][0][$m] * 100 : '';
            $list['data'][0][$m] > 0 ? $list['data'][0][$m] = $list['data'][0][$m] : '';
        }
        # 减排后 TODO
        for ($i = 0; $i < count($list['data'][0]); $i++) {
            $list['data'][1][$i] = '-';
        }
        return $list;
    }
}